#!/usr/bin/env python
# coding=utf-8
# Cron Job 列表

import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp import util
import crondb
import common

class CronListHandler(webapp.RequestHandler):
	def get(self):
		user = users.get_current_user()
		if user:
			if users.is_current_user_admin():
				self.response.headers["Content-Type"] = "text/html; charset=utf-8"
				self.writeHtmlHeader()
				self.writeLoopHeader()
				crons = crondb.listCronInfo()
				if crons:
					for cron in crons:
						self.writeLoopItem(cron)
				
				self.writeLoopFooter()
			else:
				common.writeNoPermissionMessage(self)
		else:
			self.redirect(users.create_login_url(self.request.uri))

	def writeLoopItem(self, cron):
		id = cron.key().id()
		title = cron.title
		url = cron.url
		sendSucMsg = cron.sendSuccessMsg
		sendFailMsg = cron.sendFailMsg
		enabled = cron.enabled
		cron_month = cron.month
		cron_dayOfMonth = cron.dayOfMonth
		cron_dayOfWeek = cron.dayOfWeek
		cron_hours = cron.hours
		cron_minutes = cron.minutes

		self.response.out.write("<tr>")
		self.response.out.write("<td class=\"first-cell\" style=\"text-align:center;\">")
		self.response.out.write("<span>")
		self.response.out.write("<input name=\"checkboxes[]\" type=\"checkbox\" value=\"%d\" />%d</span></td>" % (id, id))
		self.response.out.write("<td class=\"first-cell\" style=\"text-align:left;\">")
		self.response.out.write("<span onclick=\"javascript:listTable.edit(this, 'ajax_edit_title', %d)\">" % id)
		self.response.out.write(title)
		self.response.out.write("</span>")
		self.response.out.write("</td>")
		self.response.out.write("<td class=\"first-cell\" style=\"text-align:left;\">")
		self.response.out.write("<span onclick=\"javascript:listTable.edit(this, 'ajax_edit_url', %d)\">" % id)
		self.response.out.write(url)
		self.response.out.write("</span>")
		self.response.out.write("</td>")
		self.response.out.write("<td align=\"first-cell\" style=\"text-align:center;\">")
		self.response.out.write("<span onclick=\"javascript:listTable.toggle(this, 'ajax_edit_sendokmsg', %d)\">" % id)
		if sendSucMsg:
			self.response.out.write("<img src=\"images/yes.gif\" alt=\"\" title=\"\" />")
		else:
			self.response.out.write("<img src=\"images/no.gif\" alt=\"\" title=\"\" />")
		self.response.out.write("</span>")
		self.response.out.write("</td>")
		self.response.out.write("<td align=\"first-cell\" style=\"text-align:center;\">")
		self.response.out.write("<span onclick=\"javascript:listTable.toggle(this, 'ajax_edit_sendfailmsg', %d)\">" % id)
		if sendFailMsg:
			self.response.out.write("<img src=\"images/yes.gif\" alt=\"\" title=\"\" />")
		else:
			self.response.out.write("<img src=\"images/no.gif\" alt=\"\" title=\"\" />")
		self.response.out.write("</span>")
		self.response.out.write("</td>")
		self.response.out.write("<td align=\"first-cell\" style=\"text-align:center;\">")
		self.response.out.write("<span onclick=\"javascript:listTable.toggle(this, 'ajax_edit_enabled', %d)\">" % id)
		if enabled:
			self.response.out.write("<img src=\"images/yes.gif\" alt=\"\" title=\"\" />")
		else:
			self.response.out.write("<img src=\"images/no.gif\" alt=\"\" title=\"\" />")
		self.response.out.write("</span>")
		self.response.out.write("</td>")
		self.response.out.write("<td style=\"text-align:center; vertical-align:middle;\" nowrap=\"nowrap\">")
		self.response.out.write("<a href=\"editcron?id=%d\"><img src=\"images/icon_edit.gif\" alt=\"\" title=\"Edit Cron Job\" style=\"width:16px;height:16px;border:none;\" /></a>" % id)
		self.response.out.write("&nbsp;<a href=\"deletecron?id=%d\"><img src=\"images/icon_drop.gif\" alt=\"\" title=\"Delete Cron Job\" style=\"width:16px;height:16px;border:none;\" onclick=\"javascript: return confirm('Are you sure to delete?');\" /></a>" % id)
		self.response.out.write("</td>")
		self.response.out.write("</tr>")

	def writeLoopHeader(self):
		self.response.out.write("""<body>
<div>
<h1>
	<span class="action-span"><a href="createcron">Create Cron Job</a></span><span class="action-span1"><a
		href="main">Beikx Cron</a> - Cron Job List </span>
</h1>
<div style="clear: both" />""")
		self.response.out.write("<form id=\"listForm\" action=\"/deletecron\" method=\"post\">")
		self.response.out.write("""
	<div class="list-div" id="listDiv">
	<table cellspacing="1" cellpadding="3" id="list-table" style="table-layout:fixed;word-wrap:break-word;">
	<tr>
		<th style="width:95px;">
			<input onclick="listTable.selectAll(this, &quot;checkboxes&quot;)" type="checkbox" />Cron Job ID</th>
		<th style="width:280px;">
			Title</th>
		<th>
			Url</th>
		<th style="width:80px;" title="When executed success, whether or not send message.">
			Ok Message</th>
		<th style="width:80px;" title="When executed fail, whether or not send message.">
			Fail Message</th>
		<th style="width:80px;">
			Enabled</th>
		<th style="width:80px;">
			Actions</th>
	</tr>""");

	def writeLoopFooter(self):
		self.response.out.write("""<tr>
	<td colspan="2">
		<input type="submit" id="btnBatchDelete" name="btnBatchDelete" value="Batch Delete" CssClass="button" onclick="javascript:return confirm('Are you sure to delete them?');"
			disabled /></td>
	<td align="right" colspan="5" nowrap="nowrap" style="padding-right:5px;">&nbsp;</td>
</tr>
</table>
</div>
</form>
<div id="footer">
	<br />
	%s
</div>
</div>""" % common.getCopyRight())
		self.response.out.write(self.getFooterJs())
		self.response.out.write("</body></html>")

	def writeHtmlHeader(self):
		self.response.out.write("""<html>
<head>
    <title>%s</title>
    <link href="css/general.css" rel="stylesheet" type="text/css" />
    <link href="css/main.css" rel="stylesheet" type="text/css" />
    <script src="js/global.js" type="text/javascript" language="javascript"> </script>
    <script src="js/transport.js" type="text/javascript" language="javascript"></script>
    <script src="js/common.js" type="text/javascript" language="javascript"></script>
    <script src="js/utils.js" type="text/javascript" language="javascript"></script>
    <script src="js/listtable.js" type="text/javascript" language="javascript"></script>
    <script type="text/javascript" language="javascript">
    <!--
		//Ajax.debug(1,1);
        var process_request = 'Processing request...';
    // -->
    </script>
</head>""" % common.getAppName())

	def getFooterJs(self):
		return """<script type="text/javascript" language="javascript">
<!-- 
listTable.url = "ajax?is_ajax=1";
document.onmousemove=function(e)
{
  var obj = Utils.srcElement(e);
  if (typeof(obj.onclick) == 'function' && obj.onclick.toString().indexOf('listTable.edit') != -1)
  {
    obj.title = 'Click to change';
    obj.style.cssText = 'background: #278296;';
    obj.onmouseout = function(e)
    {
      this.style.cssText = '';
    }
  }
  else if (typeof(obj.href) != 'undefined' && obj.href.indexOf('listTable.sort') != -1)
  {
    obj.title = 'Click to sort';
  }
}


if (document.getElementById("listDiv"))
{
  document.getElementById("listDiv").onmouseover = function(e)
  {
    obj = Utils.srcElement(e);

    if (obj)
    {
      if (obj.parentNode.tagName.toLowerCase() == "tr") row = obj.parentNode;
      else if (obj.parentNode.parentNode.tagName.toLowerCase() == "tr") row = obj.parentNode.parentNode;
      else return;

      for (i = 0; i < row.cells.length; i++)
      {
        if (row.cells[i].tagName != "TH") row.cells[i].style.backgroundColor = '#F4FAFB';
      }
    }
  }

  document.getElementById("listDiv").onmouseout = function(e)
  {
    obj = Utils.srcElement(e);

    if (obj)
    {
      if (obj.parentNode.tagName.toLowerCase() == "tr") row = obj.parentNode;
      else if (obj.parentNode.parentNode.tagName.toLowerCase() == "tr") row = obj.parentNode.parentNode;
      else return;

      for (i = 0; i < row.cells.length; i++)
      {
          if (row.cells[i].tagName != "TH") row.cells[i].style.backgroundColor = '#FFF';
      }
    }
  }

  document.getElementById("listDiv").onclick = function(e)
  {
    var obj = Utils.srcElement(e);

    if (obj.tagName == "INPUT" && obj.type == "checkbox")
    {
      if (!document.forms['listForm'])
      {
        return;
      }
      var nodes = document.forms['listForm'].elements;
      var checked = false;
      var buttons = new Array();

      for (i = 0; i < nodes.length; i++)
      {
        if (nodes[i].checked)
        {
           checked = true;
           break;
        }
        else if (nodes[i].id && nodes[i].tagName == "INPUT" && nodes[i].id.indexOf("btnBatchDelete") != -1)
        {
            buttons.push(nodes[i]);
        }
      }
      for (; i < nodes.length; i++)
      {
        if (nodes[i].id && nodes[i].tagName == "INPUT" && nodes[i].id.indexOf("btnBatchDelete") != -1)
        {
            buttons.push(nodes[i]);
        }
      }

      for (i = 0; i < buttons.length; i++)
      {
        buttons[i].disabled = !checked;
        buttons[i].onclick = function() {
            return confirm('Are you sure to delete them?');
        };
      }
    }
  }
}
//-->
</script>"""

def main():
	application = webapp.WSGIApplication([('/cronlist', CronListHandler)],
		debug=True)
	util.run_wsgi_app(application)


if __name__ == '__main__':
	main()
